package com.qidian.mes.sso.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mes.pojo.SysUser;
import com.qidian.mes.sso.mapper.SysUserMapper;
import com.qidian.mes.sso.service.SysUserService;
import com.qidian.mes.util.JSONTools;
import com.qidian.mes.util.jwt.JWTUtil;
import com.qidian.mes.util.pojo.MESResult;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @Time 2023/11/2 9:31
 * @Description
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private JWTUtil jwtUtil; // 使用springboot的自动装配将jwtUtil对象注入到容器中
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public MESResult login(SysUser user) {
        SysUser loginUser = userMapper.getByUsename(user.getUsername());
        // 对user的密码加密后进行比较
        if(loginUser != null && loginUser.getUserPass().equals(DigestUtils.md5Hex(user.getUserPass().getBytes()))){
            //  生成token
            Map<String, String> map = new HashMap<>();
            map.put("userId",loginUser.getUserId().toString());
            map.put("username",loginUser.getUsername());
            String token = jwtUtil.getToken(map);
            // 将token放入redis, 使用token作为key, value存储token中存储的信息。
            stringRedisTemplate.opsForValue().set(token, JSONTools.object2json(map));
            // 设置时间为两小时
            stringRedisTemplate.expire(token,2, TimeUnit.HOURS);
            // 给客户端响应，将token放在MESResult的msg属性中即可
            return MESResult.ok(token);
        }
        return MESResult.fail("登陆失败");
    }
}
